#include "chatpage.h"
#include "ui_chatpage.h"
#include <QMessageBox>
#include <memory>
#include "userinfo.h"
#include <QCloseEvent>
#include "pagecontroller.h"

ChatPage::ChatPage(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ChatPage)
{
    ui->setupUi(this);
}

ChatPage::ChatPage(QWidget *parent, const QString &username, const QString &uid):
    QMainWindow(parent),
    ui(new Ui::ChatPage)
{
    ui->setupUi(this);
    userChatmode* userchatmode(new userChatmode(this,username,uid));
    userChatmode* userchatmode2(new userChatmode(this,UserInfo::getInstance()->getUserName(),UserInfo::getInstance()->getUid()));
    setUserLayout(userchatmode);
    setUserLayout(userchatmode2);
    connect(NetWorkController::getInstance(),&NetWorkController::sendMsgSig,this,&ChatPage::recvMessage);
}


void ChatPage::setUserLayout(userChatmode *userchatmode)
{
    userchatmode->setParent(this);
    ui->userLayout->addWidget(userchatmode);
    userChatVector.append(userchatmode);
}

ChatPage::~ChatPage()
{
    qDebug()<<11;
    delete ui;
}

void ChatPage::on_fontComboBox_currentFontChanged(const QFont &f)
{
    ui->textEdit->setFont(f);
    ui->textEdit_2->setFont(f);
}

void ChatPage::recvMessage(const QString &user,const QString &text)
{
    ui->textEdit->append(QString("user:%1\n%2\n").arg(user).arg(text));
}




void ChatPage::on_btn_send_clicked()
{
    QString text = ui->textEdit_2->toPlainText();
    if(text=="")
    {
        QMessageBox::warning(nullptr,"警告","请输入文字!");
        return;
    }
    else
    {
        qDebug()<<1;
        QString username=userChatVector[0]->getUsername();
        qDebug()<<"username:"<<username;
        if(NetWorkController::getInstance()->sendChatMessage(username,text))
        {
            ui->textEdit->append(QString("user:%1\n%2\n").arg(UserInfo::getInstance()->getUserName()).arg(text));
        }

    }
}








void ChatPage::on_btn_cancle_clicked()
{
    PageController::Getinstance()->closeChatPage();
}

void ChatPage::closeEvent(QCloseEvent *ev)
{
    qDebug()<<"close";
    PageController::Getinstance()->closeChatPage();
}

